package com.jiezuo.flowable.listener;

import com.alibaba.fastjson.JSONObject;
import com.jiezuo.common.exception.BusinessRuntimeException;
import com.jiezuo.common.util.StringUtil;
import com.jiezuo.common.vo.Result;
import com.jiezuo.flowable.entity.MyFormInformation;
import com.jiezuo.common.utils.SpringUtil;
import com.jiezuo.flowable.entity.MyNotify;
import com.jiezuo.flowable.entity.MyNotifySetting;
import com.jiezuo.flowable.mapper.CommonMapper;
import com.jiezuo.flowable.service.MyNotifyService;
import com.jiezuo.flowable.service.MyNotifySettingService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.impl.context.Context;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @description 公共知会监听器
 * @author 庞留杰
 * @date 2024/9/24 11:02
 * @version V1.0
 **/
@Slf4j
@Component
public class CommonNotifyListener implements JavaDelegate {

//    Expression type;
//    Expression content;
//    //用户ID，多个用“,”隔开
//    Expression users;
//    // 岗位ID，多个用“,”隔开
//    Expression positions;
//    //部门ID，多个用“,”隔开
//    Expression depts;
//    //可执行的sql语句
//    Expression sql;

    Expression setting_id;
    //变量：发起人
    final static String INITIATOR="\\$initiator";

    @Override
    public void execute(DelegateExecution execution) {
        System.out.println(">>>>>>>>>>>>>>>>公共知会监听器>>>>>>>>>>>>>>>>>>>>");
        System.out.println("execution = " + execution);
        String activityId = execution.getCurrentActivityId().trim();
        RuntimeService runtimeService = Context.getProcessEngineConfiguration().getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
        String startUserId = processInstance.getStartUserId();
        String processInstanceId = processInstance.getProcessInstanceId();
        /*String meg_type = type != null ? type.getExpressionText() : null;
        String meg_content = content != null ? content.getExpressionText() : null;
        String meg_users = users != null ? users.getExpressionText() : null;
        String meg_positions = positions != null ? positions.getExpressionText() : null;
        String meg_depts = depts != null ? depts.getExpressionText() : null;
        String meg_sql = sql != null ? sql.getExpressionText() : null;*/
        String settingId = setting_id != null ? setting_id.getExpressionText() : null;
        if (!StringUtil.isNotEmpty(settingId)) {//这个值不为空，继续向下走
            return;
        }
        MyNotifySettingService notifySettingService = SpringUtil.getObject(MyNotifySettingService.class);
        MyNotifySetting notifySetting = notifySettingService.getById(settingId);
        CommonMapper commonMapper = SpringUtil.getObject(CommonMapper.class);
        HashSet<String> receivers = new HashSet<>();//需要接收的用户（去重，无序）
        String initiator = notifySetting.getInitiator();
        String meg_title = notifySetting.getTitle();
        String meg_content = notifySetting.getContent();
        String meg_users = notifySetting.getUsers();
        String meg_positions = notifySetting.getPositions();
        String meg_depts = notifySetting.getDepts();
        String meg_sql = notifySetting.getCustom_sql();
        if (StringUtil.isNotEmpty(notifySetting.getContent())) {
            MyFormInformation form = commonMapper.findFormByProcessInstanceId(processInstanceId);
            JSONObject obj = JSONObject.parseObject(form.getData());
            for(Map.Entry<String, Object> entry : obj.entrySet()) {
                String key = "\\$" + entry.getKey();
                String value = String.valueOf(entry.getValue());
                meg_content = meg_content.replaceAll(key, value);
            }
        }
        // 是否知会发起人
        if ("1".equals(initiator)) {
            receivers.add(startUserId);
        }
        //人员
        if (StringUtil.isNotEmpty(meg_users)) {
            String[] userIds = meg_users.split(",");
            receivers.addAll(Arrays.asList(userIds));
        }
        //岗位
        if (StringUtil.isNotEmpty(meg_positions)) {
            String[] positions = meg_positions.split(",");
            List<String> users = commonMapper.findUsersByPositions(Arrays.asList(positions));
            if (users.size() > 0) {
                receivers.addAll(users);
            }
        }
        //部门
        if (StringUtil.isNotEmpty(meg_depts)) {
            String[] depts = meg_depts.split(",");
            List<String> users = commonMapper.findUsersByDepts(Arrays.asList(depts));
            if (users.size() > 0) {
                receivers.addAll(users);
            }
        }
        //sql
        if (StringUtil.isNotEmpty(meg_sql)) {
            String sql = meg_sql.replaceAll(INITIATOR, startUserId);
            List<String> users = commonMapper.findUsersBySql(sql);
            if (users.size() > 0) {
                receivers.addAll(users);
            }
        }
        // 保存消息
        //  Map<String, Object> model = commonMapper.findModelByProcessInstanceId(processInstanceId);
        //  String modelName = String.valueOf(model.get("NAME_"));
        //  String modelKey = String.valueOf(model.get("KEY_"));
        List<MyNotify> notifys = new ArrayList<>();
        for (String receiver : receivers) {
            MyNotify myNotify = new MyNotify();
            myNotify.setTitle(meg_title);
            myNotify.setContent(meg_content);
            myNotify.setProcess_instance_id(processInstanceId);
            myNotify.setReceiver(receiver);
            myNotify.setPublisher("10000");
            myNotify.setRelease_date(new Date());
            myNotify.setIs_check("0");
            myNotify.setSetting_id(settingId);
            myNotify.setContent(meg_content);
//            myNotify.setType(meg_type);
//            myNotify.setModel_key(modelKey);
//            myNotify.setModel_name(modelName);
            notifys.add(myNotify);
        }
        MyNotifyService myNotifyService = SpringUtil.getObject(MyNotifyService.class);
        boolean b = myNotifyService.saveBatch(notifys);
        System.out.println("b = " + b);
        // 发送消息
        send(notifys);
    }

    // 发送消息
    void send(List<MyNotify> notifys) {
        if (notifys != null && notifys.size() > 0) {
            //发送消息提醒
//            WSClient wsClient = SpringUtil.getObject(WSClient.class);
//            List<Map<String, String>> convert = convert(notifys);
//            Result sent = wsClient.batchPushNotify(convert);
//            if (!sent.isSuccess()) {
//                throw new BusinessRuntimeException(sent.getMessage());//调用失败，抛出异常
//            }
        }
    }

//    public List<Map<String, String>> convert(List<MyNotify> list) {
//        List<Map<String, String>> listMap = new ArrayList<>();
//        try {
//            for (MyNotify entity : list) {
//                Map<String, String> map = BeanUtils.describe(entity);
//                listMap.add(map);
//            }
//        } catch (Exception e) {
//            throw new BusinessRuntimeException(e.getMessage());
//        }
//        return listMap;
//    }

}
